package com.yunxin.facerecognition.activity;

import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.databinding.DataBindingUtil;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.common.activity.BaseActivity;
import com.common.network.help.Error;
import com.common.widget.NetworkToast;
import com.yunxin.facerecognition.R;
import com.yunxin.facerecognition.databinding.FaceRecognitionActivityVerifySignInBinding;
import com.yunxin.facerecognition.network.operate.FaceRecognitionFileUploadOperateRequest;
import com.yunxin.facerecognition.network.original.faceRecognition.CheckFaceOriginal;
import com.yunxin.facerecognition.network.request.faceRecognition.UploadFileRequest;
import com.yunxin.facerecognition.network.response.freceRecognition.CheckFaceResponse;
import com.yunxin.facerecognition.service.BackgroundCameraService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;


/**
 * author : Administrator
 * e-mail : 254419013@qq.com
 * time   : 2017/11/07
 * desc   :签到
 */
public class VerifySignInActivity extends BaseActivity {

    private static final String TAG = "VerifySignInActivity";
    public static FaceRecognitionActivityVerifySignInBinding binding;


    private AudioManager audio;
    private int currentMode;

    private Intent intentToService;
    private boolean mIsBound = false;
    private final ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            Log.d(TAG, "onServiceContected");
            mIsBound = true;
            //start service after connected
            startService(intentToService);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            Log.d(TAG, "onServiceDisconnected");
            mIsBound = false;
        }

    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        binding = DataBindingUtil.setContentView(this, R.layout.face_recognition_activity_verify_sign_in);

        initData();

        //startTakingPhotos();

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("mIsBound", mIsBound);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mIsBound = savedInstanceState.getBoolean("mIsBound");
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy()");
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        stopTakingPhotos();

    }

    private void initData() {
        audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        currentMode = audio.getRingerMode();
        intentToService = new Intent(getBaseContext(), BackgroundCameraService.class);
        intentToService.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        NotificationManager notificationManager =
                (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
                && !notificationManager.isNotificationPolicyAccessGranted()) {

            Intent intent = new Intent(
                    android.provider.Settings
                            .ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);

            startActivity(intent);
        }else {
            startTakingPhotos();
        }
    }

    private void startTakingPhotos() {
        //go into silent mode
        audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        if (!mIsBound) {
            bindService(
                    intentToService,
                    connection,
                    Context.BIND_AUTO_CREATE);
            //do not do  mIsBound==true;
        }
    }

    private void stopTakingPhotos() {
        audio.setRingerMode(currentMode);
        if (mIsBound) {
            unbindService(connection);
            //must set mIsBound=false
            mIsBound = false;
        }
        stopService(new Intent(getBaseContext(), BackgroundCameraService.class));
    }

    public static void uploadFileReq(File file) {

        binding.floatLlDescribe.setVisibility(View.VISIBLE);
        binding.floatTvDescribe.setText("照片正在识别中...");

        Glide.with(binding.floatLlDescribe.getContext())
                .load(file)
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        binding.floatIvPhoto.setImageDrawable(resource);
                        binding.floatIvPhoto.setPivotX(binding.floatIvPhoto.getWidth()/2);
                        binding.floatIvPhoto.setPivotY(binding.floatIvPhoto.getHeight()/2);//支点在图片中心
                        binding.floatIvPhoto.setRotation(180);
                    }
                });
        UploadFileRequest uploadFileRequest = new UploadFileRequest(new CheckFaceResponse(), new CheckFaceOriginal());

        uploadFileRequest.setHttpUrl("http://47.101.43.227:6662/api.php/Index/");

        uploadFileRequest.setFileUrl("http://47.101.43.227:6662/api.php/Index/checkFace");

        //上传的文件

        if (file.exists()) {

            uploadFileRequest.setFileUpload(file);

            FaceRecognitionFileUploadOperateRequest.instance().faceRecognitionFileUpload(uploadFileRequest, file.getName());
        } else {
            Log.d(TAG, "该文件不存在");
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void uploadFileResp(CheckFaceResponse checkFaceResponse) {
        if (!TextUtils.isEmpty(checkFaceResponse.getError())) {
            Log.e(TAG, "1------------ =" + checkFaceResponse.getError());
            if (checkFaceResponse.getError().equals(Error.ERROR_NETWORK_IS_NOT_AVAILABLE)
                    || checkFaceResponse.getError().equals(Error.ERROR_NET_TIMEOUT)) {
                NetworkToast.makeText(getApplicationContext()).show();
            } else {
                //其他错误
                binding.floatTvDescribe.setText(checkFaceResponse.getError());
                Toast.makeText(this, checkFaceResponse.getError(), Toast.LENGTH_SHORT).show();
                finish();
            }
        } else {
            CheckFaceOriginal checkFaceOriginal = checkFaceResponse.getData();
            if (checkFaceOriginal != null) {
                stopTakingPhotos();
                Log.e(TAG, "1------------ =" + checkFaceOriginal.getMsg());
                binding.floatRlInfo.setVisibility(View.VISIBLE);
                binding.floatTvDescribe.setText("");
                binding.floatTvUsername.setText(checkFaceOriginal.getUsername());
                binding.floatTvCompany.setText(checkFaceOriginal.getCompany());
                binding.floatTvMobile.setText(checkFaceOriginal.getMobile());
            }
        }
    }


}
